#File Name: FullWDITransparencyJAGSExport.r
#Author: James Hollyer
#Date: 04/03/2013
#Purpose: To extract the transparency index previously constructed from an
#IRT analysis on the missingness of WDI data in JAGS.
#Data Input: TransparencyIndex.RData
#OS: Windows 

setwd("c:/users/james/desktop/dropbox/transparency_and_democracy/transparencyindex/PAReplicationMaterials/Index Properties/")

library(R2jags)
library(rjags)
library(arm)
library(foreign)

load("TransparencyIndex2013.RData")

attach.jags(results)

transparencyindex<-c(1:3875)

transparencyfirstdiff<-array(NA, dim=c(2000,125,31))

for (n in 1:125){
  for (j in 2:31){
  transparencyfirstdiff[,n,j]<-transparency[,n,j] - transparency[,n,(j-1)]
  }
}

transdiff<-c(1:3875)

k<-0 
for (n in 1:125){
  k<-k+1
  transdiff[k]<-NA
  for (j in 2:31){
  k<-k+1
  transdiff[k]<-mean(transparencyfirstdiff[,n,j])
  }
}

transdifflb<-c(1:3875)
transdiffub<-c(1:3875)

transdiffHPD<-cbind(transdifflb,transdiffub)

k<-0 
for (n in 1:125){
  k<-k+1
  transdiffHPD[k,]<- c(NA,NA)
  for (j in 2:31){
  k<-k+1
  transdiffHPD[k,]<-HPDinterval(as.mcmc(as.matrix(transparencyfirstdiff[,n,j])))
  }
}


k<-0
for (n in 1:125){
  for (j in 1:31){
k<-k+1  
transparencyindex[k]<-(mean(transparency[,n,j]))
}}

transparencyindexlb<-c(1:3875)
transparencyindexub<-c(1:3875)

transparencyindexHPD<-cbind(transparencyindexub, transparencyindexlb)

k<-0
for (n in 1:125){
  for (j in 1:31){
k<-k+1  
transparencyindexHPD[k,]<-HPDinterval(as.mcmc(as.matrix(transparency[,n,j])))
}}

transparencyindexsd <- c(1:3875)

k<-0
for (n in 1:125){
  for (j in 1:31){
  k<-k+1
  transparencyindexsd[k] <-(sd(transparency[,n,j]))
}}

transparency.data<-data.frame(WDIdata$countryname, WDIdata$countrycode, WDIdata$year, transparencyindex,
transparencyindexHPD, transparencyindexsd, transdiff, transdiffHPD)
write.dta(transparency.data, file="HRV2013.dta")